<!-- 通用资源上传组件 -->
<template>
  <div class="w-main" :class="isCenter ? 'flex-center' : ''">
    <el-upload
      class="upload-demo"
      v-if="!form[resourceKey]"
      drag
      :accept="accept"
      :action="UPLOAD_URL"
      :data="uploadData"
      :limit="1"
      :on-exceed="handleExceed"
      :before-upload="file => handleBeforeResourceUpload({ file, fileType: accept })"
      :on-success="(response: IUpdateSuccessData, file: UploadFile) => handleResourcesUploadSuccess(response, file, successCallback)"
      :on-error="handleResourcesUploadError">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">{{ suggestInfo }}</div>
      </template>
    </el-upload>
    <div v-else>
      <el-button plain type="primary" @click="handleViewContractInfo">点击查看</el-button>
      <el-button plain type="danger" @click="handleDeleteContractUrl">点击删除</el-button>
    </div>
  </div>
</template>
<script setup lang="ts" generic="T extends Record<string, any>, K extends keyof T">
import { useUpload } from "@/hooks/useUpload";
import type { IUpdateSuccessData } from "@/types/upload";
import { IMG_URL, UPLOAD_URL } from "@/utils/config";
import type { UploadFile } from "element-plus";
type AcceptType = ".paf" | ".xls" | ".xlsx" | ".csv";
interface Props {
  resourceKey: K /* 资源key */;
  acceptList?: AcceptType[] /* 上传文件类型 */;
  suggestInfo?: string /* 提示信息 */;
  isCenter?: boolean /* 是否居中显示 */;
}
const { resourceKey, suggestInfo = "请上传pdf文件", acceptList = [".pdf"], isCenter = false } = defineProps<Props>();
const accept = ref<string>(acceptList.join(","));
const disabledbtn = defineModel<boolean>("disabledbtn", { required: true });
const loading = defineModel<boolean>("loading", { required: true });
const form = defineModel<T>("form", { required: true });
const emit = defineEmits<{
  handleDeleteImage: [];
  successCallback: [];
}>();
let { uploadData, handleResourcesUploadSuccess, handleBeforeResourceUpload, handleResourcesUploadError } = useUpload({ disabledbtn, loading });

/* 当超出限制时，执行的钩子函数 */
function handleExceed() {
  ElMessage.warning("只能上传一个文件");
}
/* 删除图片 */
function handleDeleteContractUrl() {
  /* 通过类型断言，明确告知ts，将""视为T[K]类型 */
  form.value[resourceKey] = "" as T[K];
  emit("handleDeleteImage");
}
/* 查看上传的资源文件信息 */
function handleViewContractInfo() {
  window.open(IMG_URL + form.value[resourceKey], "_blank");
}
/* 上传成功回调 */
function successCallback(res: IUpdateSuccessData) {
  form.value[resourceKey] = ("/" + res.key) as T[K];
  ElMessage.success("上传成功");
  emit("successCallback");
}
</script>

<style lang="scss" scoped>
.w-main {
  .upload-demo {
    text-align: center;
  }
}
.flex-center {
  display: flex;
  justify-content: center;
}
/* 图片上传 end */
</style>
